﻿using FictionsDownload.BLL;
using FictionsDownload.DAL;
using FictionsDownload.Enums;
using Zzw;
using FictionsDownload.Model;
using FictionsDownload.UI.PopDialog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FictionsDownload.UI
{
    public partial class FormDirectorys : Form
    {
        #region 内部变量
        private BookModel bookModel = new BookModel();
        private IDAL db = db_Fictions.Create();
        private BLL.Directory directory = new BLL.Directory();
        private BLL.Book book = new BLL.Book();
        #endregion
        #region 公共属性和事件
        public event EventHandler SetDirectory;
        public event EventHandler DownloadDirectory;
        #endregion
        #region 单例初始化
        private FormDirectorys()
        {
            InitializeComponent();
            //
            this.TopLevel = false;
            this.FormBorderStyle = FormBorderStyle.None;
            this.Show();
            //
        }
        private static FormDirectorys Instance;
        private static readonly object lockRoot = new object();
        /// <summary>
        /// 初始化实例
        /// </summary>
        public static FormDirectorys GetIntance
        {
            get
            {
                if (Instance == null)
                {
                    lock (lockRoot)
                    {
                        if (Instance == null)
                        {
                            Instance = new FormDirectorys();
                        }
                    }
                }
                return Instance;
            }
        }
        #endregion
        #region 控件初始化
        /// <summary>
        /// 窗口初始化之后，控件再做调整
        /// </summary>
        public void InitializeComponentCode()
        {
            lv_DirectorysInit();
        }
        private void lv_DirectorysInit()
        {
            this.lv_Directorys.Location = new Point(0,0);
            //控件底部和容器贴合
            this.lv_Directorys.Size = new Size(this.ClientSize.Width, this.ClientSize.Height - this.lv_Directorys.Location.Y);
            //初始化列
            lv_Directorys.View = View.Details;
            lv_Directorys.GridLines = true;
            lv_Directorys.FullRowSelect = true;
            //列头
            lv_Directorys.Columns.Add("Id", 30, HorizontalAlignment.Left);
            lv_Directorys.Columns.Add("Name", 180, HorizontalAlignment.Left);
            lv_Directorys.Columns.Add("Url", 350, HorizontalAlignment.Left);
            lv_Directorys.Columns.Add("Len", 40, HorizontalAlignment.Left);
            lv_Directorys.Columns.Add("ActiveTime", 200, HorizontalAlignment.Left);
            lv_Directorys.Columns.Add("SortIndex", 50, HorizontalAlignment.Left);
            //事件
            lv_Directorys.ListViewItemSorter = new ListViewColumnSorter() {
                SortColumn = lv_Directorys.Columns.Count-1,
            };
            lv_Directorys.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler(LvDirectorysSelectedIndexChanged);
        }
        #endregion
        private void lv_Directorys_Refresh()
        {
            //界面刷新了，那么染色的项目就跟着刷新了
            oldSelectdIndex = -1;
            List<DirectoryModel> directories = directory.GetList<DirectoryModel>(d => d.BookId == bookModel.Id && d.State == true);
            lv_Directorys.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度
            //清空数据
            lv_Directorys.Items.Clear();
            //重置排序规则_按照SortIndex字段进行排序
            ((ListViewColumnSorter)lv_Directorys.ListViewItemSorter).SortColumn = lv_Directorys.Columns.Count - 1;
            (lv_Directorys.ListViewItemSorter as ListViewColumnSorter).Order = SortOrder.Ascending;
            //添加数据
            foreach (var directory in directories)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = directory.Id.ToString();
                lvi.SubItems.Add(directory.Name);
                lvi.SubItems.Add(directory.Url);
                lvi.SubItems.Add(directory.Len.ToString());
                lvi.SubItems.Add(directory.ActiveTime.ToString());
                lvi.SubItems.Add(directory.SortIndex.ToString());
                if (directory.Read != true)
                {
                    lvi.Font = new Font(lvi.Font, FontStyle.Bold);
                }
                lv_Directorys.Items.Add(lvi);
            }
            lv_Directorys.EndUpdate();  //结束数据处理，UI界面一次性绘制。
        }
        public void SetBook(string bookId)
        {
            bookModel = book.Get<BookModel>(b => b.Id == bookId);
            lv_Directorys_Refresh();
        }
        /// <summary>
        /// 传入ID，选中指定项
        /// </summary>
        /// <param name="id"></param>
        public void SelectionDirectory(string id)
        {
            var selItems = lv_Directorys.SelectedItems;
            foreach (ListViewItem item in selItems)
            {
                item.Selected = false;
            }
            var selItem = lv_Directorys.FindItemWithText(id);
            selItem.Selected = true;
            selItem.Font = new Font(selItem.Font, FontStyle.Regular);
        }
        public void NextDirectory()
        {
            var selItems = lv_Directorys.SelectedItems;
            int selIndex = selItems[0].Index + 1;
            if (selIndex >= lv_Directorys.Items.Count)
            {
                return;
            }
            foreach (ListViewItem item in selItems)
            {
                item.Selected = false;
            }
            var selItem = lv_Directorys.Items[selIndex];
            SelectedDirectory(selItem);
        }
        public void PrevDirectory()
        {
            var selItems = lv_Directorys.SelectedItems;
            int selIndex = selItems[0].Index - 1;
            if (selIndex < 0)
            {
                return;
            }
            foreach (ListViewItem item in selItems)
            {
                item.Selected = false;
            }
            var selItem = lv_Directorys.Items[selIndex];
            SelectedDirectory(selItem);
        }
        private void SelectedDirectory(ListViewItem item)
        {
            item.Font = new Font(item.Font, FontStyle.Regular);
            item.Selected = true;
            string SelectId = item.Text;
            SetDirectory(SelectId, null);
        }
        /// <summary>
        /// 选中项发生变化时，高亮第一项的背景色，并且清除上次的高亮颜色
        /// </summary>
        private int oldSelectdIndex = -1;
        private void LvDirectorysSelectedIndexChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            var lv = sender as ListView;
            var lvSelecteds = lv.SelectedIndices;
            if (lvSelecteds.Count > 0)
            {
                if(oldSelectdIndex == -1)
                {
                    oldSelectdIndex = lvSelecteds[0];
                    lv.Items[oldSelectdIndex].BackColor = SystemColors.Highlight;
                }
                else if(oldSelectdIndex != lvSelecteds[0]) //只有多选的时候才会来到这里
                {
                    lv.Items[oldSelectdIndex].BackColor = SystemColors.Window;
                    oldSelectdIndex = lvSelecteds[0];
                    lv.Items[oldSelectdIndex].BackColor = SystemColors.Highlight;
                }
            }
            else//每次点击，都进入这里清空所有信息，然后开始多选或单选循环设置
            {
                lv.Items[oldSelectdIndex].BackColor = SystemColors.Window;
                oldSelectdIndex = -1;
            }
        }
        private void lv_Directorys_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                CmsDirectorys.Show(this, new Point(e.X, e.Y));
            }
            else
            {
                int selectCount = lv_Directorys.SelectedItems.Count;
                if (selectCount == 1)//若小于0是未选中，大于1是多选，多选不显示文本内容
                {
                    SelectedDirectory(lv_Directorys.SelectedItems[0]);
                }
            }
        }
        /// <summary>
        /// 将章节的状态隐藏显示，实际没有删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectedItems = lv_Directorys.SelectedItems;
            if (selectedItems.Count > 0)
            {
                FormDeleteDirectory tempForm = new FormDeleteDirectory();
                var result = tempForm.ShowDialog();
                if (result == (DialogResult)DeleteEnum.确定删除)
                {
                    foreach (ListViewItem item in selectedItems)
                    {
                        var dir = directory.Find<DirectoryModel>(item.Text);
                        dir.State = false;
                        directory.Update(dir);
                    }
                    directory.SaveChanges();
                    lv_Directorys_Refresh();
                }
                else if (result == (DialogResult)DeleteEnum.彻底删除)
                {
                    foreach (ListViewItem item in selectedItems)
                    {
                        var dir = directory.Find<DirectoryModel>(item.Text);
                        directory.Delete(dir);
                    }
                    directory.SaveChanges();
                    lv_Directorys_Refresh();
                }
            }
        }

        private void 下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectedItems = lv_Directorys.SelectedItems;
            if (selectedItems.Count > 0)
            {
                foreach (ListViewItem item in selectedItems)
                {
                    DownloadDirectory?.Invoke(item.Text, null);
                }
                lv_Directorys_Refresh();
            }
        }

        private void lv_Directorys_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            System.Windows.Forms.ListView lv = sender as System.Windows.Forms.ListView;
            // 检查点击的列是不是现在的排序列.
            if (e.Column == (lv.ListViewItemSorter as ListViewColumnSorter).SortColumn)
            {
                // 重新设置此列的排序方法.
                if ((lv.ListViewItemSorter as ListViewColumnSorter).Order == System.Windows.Forms.SortOrder.Ascending)
                {
                    (lv.ListViewItemSorter as ListViewColumnSorter).Order = System.Windows.Forms.SortOrder.Descending;
                }
                else
                {
                    (lv.ListViewItemSorter as ListViewColumnSorter).Order = System.Windows.Forms.SortOrder.Ascending;
                }
            }
            else
            {
                // 设置排序列，默认为正向排序
                (lv.ListViewItemSorter as ListViewColumnSorter).SortColumn = e.Column;
                (lv.ListViewItemSorter as ListViewColumnSorter).Order = System.Windows.Forms.SortOrder.Ascending;
            }
            // 用新的排序方法对ListView排序
            ((System.Windows.Forms.ListView)sender).Sort();
        }

        private void 保存排序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var items = lv_Directorys.Items;
            List<DirectoryModel> directories = new List<DirectoryModel>();
            foreach (ListViewItem item in items)
            {
                directories.Add(new DirectoryModel {
                    Id = item.SubItems[0].Text,
                    Name = item.SubItems[1].Text,
                    Url = item.SubItems[2].Text,
                    Len = item.SubItems[3].Text.ToInt(0),
                    SortIndex = item.SubItems[5].Text.ToInt(),
                });
            }
            //按照当前的顺序，对SortIndex字段进行升序排序。
            var indexs = directories.Select(m => m.SortIndex).ToList();
            indexs.Sort();
            for(int i = 0; i < directories.Count; i++)
            {
                var item = directories[i];
                var index = indexs[i];
                var dir = directory.Find<DirectoryModel>(item.Id);
                dir.SortIndex = index;
                directory.Update(dir);
            }
            directory.SaveChanges();
            MessageBox.Show("当前排序保存成功");
        }

        #region 已读未读设置
        private void 选中章节未读ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectedItems = lv_Directorys.SelectedItems;
            if (selectedItems.Count > 0)
            {
                List<string> vs = new List<string>();
                foreach (ListViewItem item in selectedItems)
                {
                    vs.Add(item.Text);
                }
                ModDirectoryRead(vs, false);
            }
        }

        private void 选中章节已读ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectedItems = lv_Directorys.SelectedItems;
            if (selectedItems.Count > 0)
            {
                List<string> vs = new List<string>();
                foreach (ListViewItem item in selectedItems)
                {
                    vs.Add(item.Text);
                }
                ModDirectoryRead(vs,true);
            }
        }
        /// <summary>
        /// 修改指定章节的阅读状态
        /// </summary>
        /// <param name="directoryIDs">指定章节ID</param>
        /// <param name="read">已读true,未读false</param>
        private void ModDirectoryRead(List<string> directoryIDs,bool read)
        {
            foreach (string item in directoryIDs)
            {
                var dir = directory.Find<DirectoryModel>(item);
                dir.Read = read;
                directory.Update(dir);
            }
            directory.SaveChanges();
            lv_Directorys_Refresh();
        }

        private void 以上章节已读ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectedItems = lv_Directorys.SelectedItems;
            if (selectedItems.Count > 0)
            {
                List<string> vs = new List<string>();
                foreach (ListViewItem item in selectedItems)
                {
                    vs.Add(item.Text);
                }
                var it = selectedItems.Cast<ListViewItem>().First();
                var items = lv_Directorys.Items;
                foreach (ListViewItem item in items)
                {
                    if(it == null || item.Text == it.Text)
                    {
                        break;
                    }
                    vs.Add(item.Text);
                }
                ModDirectoryRead(vs, true);
            }
        }

        private void 以下章节未读ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectedItems = lv_Directorys.SelectedItems;
            if (selectedItems.Count > 0)
            {
                List<string> vs = new List<string>();
                foreach (ListViewItem item in selectedItems)
                {
                    vs.Add(item.Text);
                }
                var it = selectedItems.Cast<ListViewItem>().Last();
                var items = lv_Directorys.Items;
                for(int i = it.Index+1; i < items.Count; i++)
                {
                    vs.Add(items[i].Text);
                }
                ModDirectoryRead(vs, false);
            }
        }

        private void 全部已读ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var items = lv_Directorys.Items;
            List<string> vs = new List<string>();
            foreach (ListViewItem item in items)
            {
                vs.Add(item.Text);
            }
            ModDirectoryRead(vs, true);
        }

        private void 全部未读ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var items = lv_Directorys.Items;
            List<string> vs = new List<string>();
            foreach (ListViewItem item in items)
            {
                vs.Add(item.Text);
            }
            ModDirectoryRead(vs, false);
        }
        #endregion
    }
}
